package edu.pku.sei.modeler.uml.commands;

import org.eclipse.gef.commands.Command;

import edu.pku.sei.modeler.model.structure.MetaLink;
import edu.pku.sei.modeler.model.structure.MetaNode;

public  class UMLConnectionDeleteCommand extends Command {
	protected MetaLink link;

	protected MetaNode source, target;
	
	protected boolean isDeletedFromDiagram;
	
	private ConnectionModelDeleteCommand modelCmd;
	
	public ConnectionModelDeleteCommand getModelCmd() {
		return modelCmd;
	}


	public void setModelCmd(ConnectionModelDeleteCommand modelCmd) {
		this.modelCmd = modelCmd;
	}


	public UMLConnectionDeleteCommand(MetaLink link, boolean isDeletedFromDiagram) {
		super("delete a link");
		this.link = link;
		this.source = link.getSource();
		this.target = link.getTarget();
		this.isDeletedFromDiagram = isDeletedFromDiagram;
	}


	@Override
	public boolean canExecute() {
		boolean result = source != null && target != null && link != null;
		if (modelCmd != null)
			return result && modelCmd.canExecute();
		else return result;
	}
		
	@Override
	public void execute() {

		// FIXME: This statement has an non-local-handled exception
		deleteLink();
		
		if (!isDeletedFromDiagram && modelCmd != null) {
			modelCmd.execute();
		}
		
	}


	protected void deleteLink() {
		link.setSource(null);
		link.setTarget(null);
		int srcIndex = source.getOutgoings().indexOf(link);
		int targetIndex = target.getIncomings().indexOf(link);
		if (srcIndex != -1) {
			source.getOutgoings().remove(srcIndex);
			target.getIncomings().remove(targetIndex);
		}
	
		if (source == target) {
			link.getBendPoints().clear();
		}
	}

	@Override
	public void undo() {
		
		link.setSource(source);
		source.getOutgoings().add(link);
		link.setTarget(target);
		target.getIncomings().add(link);
		link.setModel(source.getModel());
		
		if (!isDeletedFromDiagram && modelCmd != null) {
			modelCmd.undo();
		}
		
	}
}
